package com.sjme;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

@Component
public class AESUtil {
    private final SecretKeySpec keySpec;

    public AESUtil(@Value("${app.encryption.key:}") String key) {
        // 如果配置为空，生成随机密钥
        String actualKey = key.isEmpty() ? generateAndLogRandomKey() : key;

        // 确保密钥长度正确
        byte[] keyBytes = ensureKeyLength(actualKey.getBytes());
        this.keySpec = new SecretKeySpec(keyBytes, "AES");
    }

    /**
     * 确保密钥长度为16/24/32字节
     */
    private byte[] ensureKeyLength(byte[] key) {
        int requiredLength = 16; // AES-128

        if (key.length == requiredLength) {
            return key;
        }

        // 长度不足时填充，超长时截断
        byte[] newKey = new byte[requiredLength];
        int copyLength = Math.min(key.length, requiredLength);
        System.arraycopy(key, 0, newKey, 0, copyLength);

        // 如果长度不足，用随机字节填充剩余部分
        if (key.length < requiredLength) {
            byte[] randomBytes = new byte[requiredLength - key.length];
            new SecureRandom().nextBytes(randomBytes);
            System.arraycopy(randomBytes, 0, newKey, key.length, randomBytes.length);
        }

        return newKey;
    }

    /**
     * 生成随机密钥并打印到日志（便于配置）
     */
    private String generateAndLogRandomKey() {
        String randomKey = generateRandomKey(256);
        System.out.println("=== 生成的AES密钥（请保存到配置文件中）===");
        System.out.println("app.encryption.key=" + randomKey);
        System.out.println("=====================================");
        return randomKey;
    }

    private String generateRandomKey(int keySize) {
        try {
            javax.crypto.KeyGenerator keyGen = javax.crypto.KeyGenerator.getInstance("AES");
            keyGen.init(keySize);
            javax.crypto.SecretKey secretKey = keyGen.generateKey();
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException("生成密钥失败", e);
        }
    }

    public String encrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public String decrypt(String encryptedData) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decoded = Base64.getDecoder().decode(encryptedData);
            return new String(cipher.doFinal(decoded));
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }

    public static void main(String[] args) {
        AESUtil aesUtil = new AESUtil("");
        aesUtil.generateAndLogRandomKey();
    }
}